<!-- eslint-disable no-undef -->
<script setup lang="ts">
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import type { Patient } from '@/types/user'
import {
  createConsultRrderPre,
  createOrder,
  consultPay
} from '@/services/consult'
import { getPatientInfo } from '@/services/user'
import { useConsultStore } from '@/stores'
import {
  showConfirmDialog,
  showDialog,
  showLoadingToast,
  showToast
} from 'vant'
const store = useConsultStore()
const router = useRouter()
// 预支付信息
const consultPre = ref<ConsultOrderPreData>()
// 获取预支付信息
const getConsultPre = async () => {
  const res = await createConsultRrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  consultPre.value = res.data
  // 设置优惠券id
  store.setCouponId(res.data.couponId)
}
// 患者信息
const consultDetail = ref<Patient>()
// 获取患者信息
const getConsultDetail = async () => {
  const res = await getPatientInfo(store.consult.patientId as string)
  consultDetail.value = res.data
}
// 刷新的页面的时候 判断 consult模块中是否有填写的问诊记录信息
// keyof是将一个类型中的键 处理成 字面量联合类型
// type MyObj = {
//   name: string
//   age: number
//   gender: string
// }
// const obj: MyObj = { name: 'zs', age: 18, gender: 'nan' }
// type myres = keyof MyObj
// const str: myres = 'name'
// if(store.consult.type === undefined || )
type myType = keyof PartialConsult
const arr: myType[] = [
  'type',
  'illnessType',
  'illnessDesc',
  'consultFlag',
  'illnessTime',
  'pictures',
  'patientId',
  'depId'
]
const boo = arr.every((item) => store.consult[item] === undefined)
if (boo) {
  showDialog({
    title: '温馨提示',
    message: '支付信息不完整请重新填写，如果未支付可以去记录继续支付'
  }).then(() => {
    router.push('/')
  })
} else {
  getConsultPre()
  getConsultDetail()
}

const agree = ref(false)
// 控制抽屉的布尔值
const show = ref(false)
const orderId = ref('')
// 生成订单id
const cretateOrderId = async () => {
  // 1. 协议的许可
  if (!agree.value) return showToast('请勾选支付协议')
  // 2. 展示抽屉
  show.value = true
  // 3. 生成订单 携带参数发送请求
  const res = await createOrder(store.consult)
  // console.log(res)
  // 4. 清除consult仓库模块中所有的问诊信息
  store.clear()
  // 5. 记录id
  orderId.value = res.data.id
}

// 如果生成了订单id, 不允许离开这个页面了
onBeforeRouteLeave(() => {
  if (orderId.value) return false // 阻止离开这个页面
})

// 阻止抽屉关闭
const beforeClose = () => {
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      // 点击了继续支付 阻止抽屉关闭
      return false
    })
    .catch(() => {
      // 清除订单id后 扔到问诊记录页面
      orderId.value = ''
      router.push('/user/consult')
      return true // beforeClose 必须要返回一个布尔值  解决类型提示的问题
    })
}
// 支付方式 0是微信 1是支付宝
const paymentMethod = ref<0 | 1>(1)

const pay = async () => {
  // 1. loading展示
  showLoadingToast({
    message: '正在支付...',
    forbidClick: true, // 禁止背景点击
    duration: 0 // 永久展示
  })
  // 2. 发送请求 得到url地址
  const res = await consultPay({
    orderId: orderId.value,
    paymentMethod: paymentMethod.value,
    payCallback: import.meta.env.VITE_APP_CALLBACK + '/room'
  })
  // console.log(res.data.payUrl)
  // 3. 跳转到支付平台进行支付
  window.location.href = res.data.payUrl
}
</script>

<template>
  <div class="consult-pay-page" v-if="consultPre && consultDetail">
    <cp-navbar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ consultPre.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${consultPre.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${consultPre.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`-¥${consultPre.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${consultDetail.name} | ${consultDetail.genderValue} | ${consultDetail.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="consultPre.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="cretateOrderId"
    />
    <!-- 支付的抽屉 动作面板 -->
    <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :closeable="false"
      :close-on-popstate="false"
      :before-close="beforeClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ consultPre.actualPayment }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 0"
            /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 1"
            /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet>
  </div>

  <div class="consult-pay-page" v-else>
    <van-skeleton title :row="3" />
    <van-skeleton title :row="4" style="margin: 30px 0" />
    <van-skeleton title :row="3" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
